package me.feng.actors

import akka.actor.Actor
import akka.actor.Props
import me.feng.entity.Event
import me.feng.entity.EventType
import me.feng.entity.Message
import me.feng.entity.Letter
import me.feng.entity.LetterType
import me.feng.messageinbound.MainChart
import me.feng.util.CacheUtil

class MainActor extends Actor {

  def receive = {
    case msg: Message[Letter] => {
      val letter = msg.result.asInstanceOf[Letter]
      val cid = letter.cid
      letter.kind match {
        case LetterType.USER => {
          val userActor = context.actorFor(cid)
          val selfActor = context.actorFor(letter.from.id)
          userActor ! msg
          selfActor ! msg
        }

        case LetterType.MAIN => {
          context.children.foreach(f = ac => {
            ac ! msg
          })
        }

        
      }

    }

    case p: (String, MainChart) => {

      var newActor = false
      val userActor = if (!context.child(p._1).isDefined) {
        newActor = true
        println("uid 登陆：" + p._2.getUser.id)
        println("new actor:" + p._2.getUser.id)
        context.actorOf(Props(classOf[UserActor], p._2.getUser), p._2.getUser.id)
      } else
        context.child(p._1).get
      userActor ! p._2
      if (newActor) {
        CacheUtil.addOlUser(p._2.getUser)
        context.children.filter(ac => {
          !ac.path.name.equals(p._2.getUser.id)
        }).foreach(a => {
          a ! new Event(p._2.getUser, MainActor.DEFAULT_MAIN_ID, EventType.LOGIN)
        })
        userActor ! "REFRESH_ONLINE_USERS"
      }
    }

    case e: Event => {

      e.event match {
        case EventType.CLOSE => {
          CacheUtil.removeUser(e.u.id)
          context.children.filter(a => {
            a.path.name.equals(e.u.id)
          }).foreach(ac => {
            println("Kill===" + ac)
            context.system.stop(ac)
          })
          context.children.foreach(a => {
            a ! e
          })
        }
        case EventType.NEW_SESSION =>{
          context.actorFor(e.eid) ! e
        }
        
        case _ => context.actorFor(e.eid) ! e
      }

    }
  }
}

object MainActor {
  val DEFAULT_MAIN_ID = "0"
}